<!--刘川中-->
<!--2017/12/06-->
<template>
  <section>
    <!--类型选择 start-->
    <el-col :span="23" class="mt-2">
      <el-form>
        <el-form-item class="mb-2">
          <el-button type="default"
                     :class="currentFreightType.value == freightTypes[0]?'el-button--primary':''"
                     :loading="currentFreightType.value == freightTypes[0] && visible.freightTypeLoading"
                     @click.native="editFreightType(freightTypes[0])">按商品累加运费
          </el-button>
          <el-button type="default"
                     :class="currentFreightType.value == freightTypes[1]?'el-button--primary':''"
                     :loading="currentFreightType.value == freightTypes[1] && visible.freightTypeLoading"
                     @click.native="editFreightType(freightTypes[1])">组合运费(按订单最高运费计算)
          </el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <el-col :span="1" class="mt-2">
      <el-form>
        <el-form-item class="mb-2">
          <el-button type="primary" icon="el-icon-plus" @click="visible.addForm = true">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <!--类型选择 end-->

    <!--折叠面板表格 start-->
    <el-col>
      <el-collapse @change="" style="background-color: #fff" v-for="(item, index) in freightList" :key="index">
        <el-collapse-item>
          <template slot="title">
            <el-row style="background-color: #eef2fd" class="px-2">
              <el-col :span="22" style="font-weight: 600">{{item.template_name}}</el-col>
              <el-col :span="1" @click.native.stop="handleDeleteAll(item)">
                <a href="javascript:" class="color-blue">删除</a>
              </el-col>
            </el-row>
          </template>
          <el-col class="px-2">
            <el-table :data="item.rule" :highlight-current-row="true" v-loading="visible.listLoading"
                      style="width: 100%;" max-height="800">
              <!--<el-table-column type="index" width="50"></el-table-column>-->
              <el-table-column prop="area" label="可配送区域">
                <template slot-scope="scope">
                  <el-col style="max-height: 200px; overflow-y: auto">{{scope.row.area.distinct_name}}</el-col>
                </template>
              </el-table-column>
              <el-table-column prop="first_num" label="首件（个）" width="120" sortable></el-table-column>
              <el-table-column prop="first_cost" label="运费（元）" width="120" sortable></el-table-column>
              <el-table-column prop="more_num" label="续件（个）" width="120" sortable></el-table-column>
              <el-table-column prop="more_cost" label="续费（元）" width="120" sortable></el-table-column>
              <el-table-column label="操作" width="120">
                <template slot-scope="scope">
                  <el-button size="small" type="primary" icon="el-icon-edit" class="btn-circle"
                             @click="showEditForm(item, scope.row, 'edit')"></el-button>
                  <el-button size="small" type="danger" icon="el-icon-delete" class="btn-circle"
                             @click="handleDelete(scope.row)"></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col class="my-4">
            <a href="javascript:" class="color-blue ml-3" @click="showEditForm(item, null, 'add')">
              <i class="el-icon-plus"></i> 添加配送区域
            </a>
            <!--<el-button type="primary" icon="el-icon-plus" @click.native="showEditForm(item, null, 'add')">新增配送区域</el-button>-->
          </el-col>
        </el-collapse-item>
      </el-collapse>
    </el-col>
    <!--折叠面板表格 end-->


    <!--表格start -->
    <el-table :data="freightList" :highlight-current-row="true" v-loading="visible.listLoading" style="width: 100%;"
              @sort-change="" hidden>
      <el-table-column type="index" width="100">
      </el-table-column>
      <el-table-column prop="template_name" label="品牌名">
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" sortable="custom">
      </el-table-column>
      <el-table-column label="品牌logo" prop="brand_pic">
        <template slot-scope="scope">
          <a :href="scope.row.full_image" target="_blank"><img :src="scope.row.full_image"
                                                               class="list-brand-image"/></a>
        </template>
      </el-table-column>
      <el-table-column prop="brand_desc" label="简介">
      </el-table-column>

      <el-table-column label="操作" width="250">
        <template slot-scope="scope">
          <el-button size="small" type="primary" @click="showEditForm(scope.$index, scope.row)" icon="el-icon-edit">编辑
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)" icon="el-icon-edit">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--表格end -->
    <!--分页start -->
    <el-col :span="24" class="toolbar" hidden>
      <el-pagination layout="total, sizes, prev, pager ,next" :page-size="filters.pageSize"
                     :total="pagination.total"
                     @current-change="handlePageChange" @size-change="handleSizeChange">
      </el-pagination>
    </el-col>
    <!--分页start -->

    <!--新增 start -->
    <el-dialog :visible.sync="visible.addForm" width="30%" :before-close="hiddenAddForm">
      <div class="dialog-title" slot="title">新增运费模板</div>
      <el-form :model="addForm" label-width="100px" ref="addForm" :rules="addFormRules">
        <el-form-item label="模板名称" prop="template_name">
          <el-input v-model="addForm.template_name" auto-complete="off" :maxlength="20" width="20"
                    placeholder="模板名称"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hiddenAddForm">取消</el-button>
        <el-button type="primary" @click="handleAdd" :loading="visible.addTemplateNameLoading">提交</el-button>
      </div>
    </el-dialog>
    <!--新增 end -->

    <!--编辑 start -->
    <el-dialog :visible="visible.editForm" width="50%" :before-close="hiddenEditForm">
      <div class="dialog-title" slot="title" v-show="editFormOptionType==='add'">新增配送区域</div>
      <div class="dialog-title" slot="title" v-show="editFormOptionType==='edit'">编辑配送区域</div>
      <el-form :model="editForm" label-width="100px" ref="editForm" :rules="editFormRules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="模板名" prop="template_name">
              <el-input v-model="editForm.template_name" auto-complete="off" :maxlength="20" width="20"
                        :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="配送区域" prop="area">
              <el-tree ref="editAreas" :data="areaList" :props="areaProps" show-checkbox
                       node-key="area_id" :expand-on-click-node="true" lazy
                       :load="loadNode" :default-expanded-keys="expandedKeys"
                       style="max-height: 400px; overflow-y: auto"></el-tree>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="首件（个）" prop="first_num">
              <el-input-number v-model="editForm.first_num" @change="" :min="1" :max="9999999999"
                               label=""></el-input-number>
            </el-form-item>
            <el-form-item label="运费（元）" prop="first_cost">
              <el-input-number v-model="editForm.first_cost" @change="" :min="0" :max="9999999999"
                               label=""></el-input-number>
            </el-form-item>
            <el-form-item label="续件（个）" prop="more_num">
              <el-input-number v-model="editForm.more_num" @change="" :min="1" :max="9999999999"
                               label=""></el-input-number>
            </el-form-item>
            <el-form-item label="续费（元）" prop="more_cost">
              <el-input-number v-model="editForm.more_cost" @change="" :min="0" :max="9999999999"
                               label=""></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hiddenEditForm">取消</el-button>
        <el-button type="primary" @click="handleEdit" :loading="visible.editLoading">提交</el-button>
      </div>
    </el-dialog>
    <!--编辑 end -->
  </section>
</template>
<script>
  import {
    addFreightName, delFreightItem, getFreightList, getAreas,
    addFreightRule, editFreightRule, delFreightRule, getSettings, editSettings
  } from '../../api/api'

  export default {
    data () {
      return {
        freightTypes: ['0', '1'],
        freightList: [],
        filters: {
          pageSize: 1000,
          page: 1,
          sort: ''
        },
        currentFreightType: '',
        pagination: {
          total: 0
        },
        visible: {
          addForm: false,
          addTemplateNameLoading: false,
          editForm: false,
          listLoading: false,
          editLoading: false,
          freightTypeLoading: false
        },
        addForm: {
          template_name: ''
        },
        editForm: {
          rule_id: '',
          template_name: '',
          area: '',
          first_num: 1,
          first_cost: 0,
          more_num: 1,
          more_cost: 0
        },
        areaProps: {
          key: 'area_id',
          label: 'area_name',
          children: 'children',
          isLeaf: 'leaf'
        },
        expandedKeys: [], // 默认展开的节点
        areaList: [],     // 一级区域列表
        checkedIds: [],   //  选中的节点id列表
        addFormRules: {
          template_name: [
            {required: true, message: '请输入模板名', trigger: 'blur'}
          ]
        },
        editFormRules: {
          area: [],
          first_num: [{pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入合法的数量', trigger: 'blur'}],
          first_cost: [{
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: '请输入合法的金额',
            trigger: 'blur'
          }],
          more_num: [{pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入合法的数量', trigger: 'blur'}],
          more_cost: [{
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: '请输入合法的金额',
            trigger: 'blur'
          }]
        },
        editFormOptionType: 'add',
        selectAllAreaFlag: false, // 是否全选所有配送区域
        loadNodeTimes: 0 // 是否正在设置选中的keys（因为查找keys是递归查找，要防止多次调用）
      }
    },
    methods: {
      // 编辑运费方式
      editFreightType (type) {
        if (this.visible.freightTypeLoading || type === this.currentFreightType.value) return
        this.$confirm('确认修改运费的计费方式？', '提示', {}).then(valid => {
          if (valid) {
            this.currentFreightType.value = type
            this.visible.freightTypeLoading = true
            editSettings([this.currentFreightType]).then(res => {
              if (res.status === 1) {
                this.$message({
                  message: '修改计费方式成功',
                  type: 'success'
                })
              } else {
                this.$message({
                  message: '修改失败',
                  type: 'error'
                })
                this.currentFreightType.value = ''
              }
              this.visible.freightTypeLoading = false
            })
          }
        }).catch(() => {
        })
      },
      // 获取分类列表
      handleAreas () {
        getAreas({area_pid: ''}).then(res => {
          if (res.status === 1) {
            this.areaList = res.data
            // 如果是新增则全部选中
            if (this.selectAllAreaFlag) {
              this.$nextTick(function () {
                this.$refs['editAreas'].setCheckedNodes(this.areaList)
              })
            }
          }
        })
      },
      // 加载城市子节点
      loadNode: function (node, resolve) {
        if (node.level === 0) {
          resolve(this.areaList)
          // expandedKeys为空的情况，就不会执行下面else的语句
          if (this.expandedKeys.length === 0) {
            this.$nextTick(function () {
              this.$refs['editAreas'].setCheckedKeys(this.checkedIds)
              // 重新计数
              this.loadNodeTimes = 0
            })
          }
        } else if (node.level <= 2) {
          getAreas({area_pid: node.data.area_id}).then(res => {
            // 配送区域只有三级，第三级为叶子节点
            if (node.level === 2) {
              res.data.map((item) => {
                item.leaf = true
              })
            }
            resolve(res.data)
            if (this.loadNodeTimes === this.expandedKeys.length - 1) {
              // 展开节点最后一次请求的时候再设置选中的节点，性能最好
              this.$nextTick(function () {
                this.$refs['editAreas'].setCheckedKeys(this.checkedIds)
                // 重新计数
                this.loadNodeTimes = 0
              })
            } else {
              this.loadNodeTimes++
            }
          })
        } else {
          resolve([])
        }
      },
      // 递归遍历找到所有选中的元素的id - 不用了
      findCheckedNodeIds: function (areaList) {
        for (let i = 0; i < areaList.length; i++) {
          let item = areaList[i]
          if (item.checked === true) {
            this.checkedIds.push(item.area_id)
          } else {
            if (item.children !== undefined && item.children.length > 0) {
              this.findCheckedNodeIds(item.children)
            }
          }
        }
        return this.checkedIds
      },
      // 设置默认展开的key, 如110105，则返回[11, 1101]
      getExpandedKeys: function (list) {
        let arr = []
        list.map((item) => {
          let str = item + ''
          let times = Math.floor(str.split('').length / 2)
          for (let i = 1; i < times; i++) {
            str = str.substring(0, str.split('').length - 2)
            arr.push(parseInt(str))
          }
        })
        // 数组去重
        arr = [...new Set([...arr])]
        return arr.sort()
      },
      // 显示编辑表单
      showEditForm (item, row, type) {
        this.editFormOptionType = type
        this.visible.editForm = true
        this.expandedKeys = []
        try {
          // 重置表单（可能会报错）
          this.$refs['editForm'].resetFields()
        } catch (e) {}
        if (type === 'add') {
          // 重新请求区域数据，防止缓存
          this.handleAreas()
          this.selectAllAreaFlag = true
          this.editForm.template_id = item.template_id
        } else {
          this.selectAllAreaFlag = false
          this.checkedIds = JSON.parse(row.area.distinct_ids)
          this.editForm = {
            rule_id: row.rule_id,
            template_id: row.template_id,
            template_name: row.template_name,
            area: row.area.distinct_ids,
            first_num: row.first_num,
            first_cost: row.first_cost,
            more_num: row.more_num,
            more_cost: row.more_cost
          }
          try {
            // 选中的节点置为空（可能会报错）
            // this.$refs['editAreas'].setCheckedKeys([]);
          } catch (e) {}
          this.$nextTick(() => {
            // 设置展开的keys
            this.expandedKeys = this.getExpandedKeys(this.checkedIds)
            this.$refs['editAreas'].setCheckedKeys(this.checkedIds)
          })
        }
        this.editForm.template_name = item.template_name
      },
      // 新增
      handleAdd () {
        this.$refs['addForm'].validate((valid) => {
          if (valid) {
            this.visible.addTemplateNameLoading = true
            addFreightName(this.addForm).then(res => {
              if (res.status === 1) {
                this.handleList()
                this.visible.addForm = false
                this.$refs['addForm'].resetFields()
                this.$message({
                  message: '新增成功',
                  type: 'success'
                })
              } else if (res.errorCode === 10005) {
                this.$message({
                  message: '新增失败: 该模板名已经存在。',
                  type: 'error'
                })
              }
              this.visible.addTemplateNameLoading = false
            })
          }
        })
      },
      // 删除整个模板分类
      handleDeleteAll (row) {
        this.$confirm(`确认删除 <${row.template_name}> 模板分类？`, '提示', {}).then(valid => {
          if (valid) {
            delFreightItem(row.template_id).then(res => {
              if (res.status === 1) {
                this.$message({
                  message: '删除成功',
                  type: 'success'
                })
                this.handleList()
              }
            })
          }
        }).catch(() => {
        })
      },
      // 删除模板分类下的一条规则
      handleDelete (row) {
        this.$confirm('确认删除？', '提示', {}).then(valid => {
          if (valid) {
            delFreightRule(row.rule_id).then(res => {
              if (res.status === 1) {
                this.$message({
                  message: '删除成功',
                  type: 'success'
                })
                this.handleList()
              } else {
                this.$message({
                  message: '删除失败: ' + res.errorMsg,
                  type: 'error'
                })
              }
            })
          }
        }).catch(() => {
        })
      },
      // 编辑
      handleEdit () {
        this.editForm.area = JSON.stringify(this.$refs['editAreas'].getCheckedKeys())
        if (this.editForm.area === '[]') {
          this.$message({
            message: '配送区域不能为空',
            type: 'error'
          })
          return false
        }
        // 如果省市已经全选了，那么它的子级就没必要传给服务器了
        let ids = this.$refs['editAreas'].getCheckedKeys()
        ids.map((value, index) => {
          // console.log(value, index);
        })
        this.$refs['editForm'].validate(valid => {
          if (valid) {
            this.visible.editLoading = true
            if (this.editFormOptionType === 'add') {
              addFreightRule(this.editForm).then(res => {
                if (res.status === 1) {
                  this.$message({
                    message: '新增配送区域成功',
                    type: 'success'
                  })
                  this.visible.editForm = false
                  this.handleList()
                } else {
                  this.$alert('修改失败: ' + res.errorMsg, '错误', {type: 'error'})
                }
                this.visible.editLoading = false
              })
            } else {
              editFreightRule(this.editForm).then(res => {
                if (res.status === 1) {
                  this.$message({
                    message: '修改成功',
                    type: 'success'
                  })
                  this.handleList()
                  this.visible.editForm = false
                } else {
                  this.$alert('修改失败: ' + res.errorMsg, '错误', {type: 'error'})
                }
                this.visible.editLoading = false
              })
            }
          }
        })
      },
      // 隐藏新增表单
      hiddenAddForm () {
        this.visible.addForm = false
      },
      // 隐藏编辑表单
      hiddenEditForm () {
        this.visible.editForm = false
        // 重新请求区域数据，防止缓存
        this.handleAreas()
        this.expandedKeys = []
      },
      // 获取列表
      handleList () {
        if (this.visible.listLoading) return
        this.visible.listLoading = true
        getFreightList(this.filters).then(res => {
          if (res.status === 1) {
            this.freightList = res.data
            this.visible.listLoading = false
            // this.pagination.total = res.totalCount;
          } else {
            this.$message({
              message: res.message,
              type: 'error'
            })
          }
        })
      },
      // 重置搜索列表
      handleRestFilters () {
        this.filters = {
          pageSize: 1000,
          page: 1,
          sort: '',
          expand: 'ruleArea'
        }
        this.handleList()
      },
      // 页码改变
      handlePageChange (page) {
        this.filters.page = page
        this.handleList()
      },
      // 分页条数改变
      handleSizeChange (size) {
        this.filters.pageSize = size
        this.handleList()
      }
    },
    mounted () {
      this.visible.freightTypeLoading = true
      getSettings({prefix: 'shipping'}).then(res => {
        this.visible.freightTypeLoading = false
        if (res.status === 1) {
          this.currentFreightType = res.data[0]
        }
      })
      this.handleList()
      this.handleAreas()
    }
  }
</script>
<style rel="stylesheet/sass" lang="sass" scoped>

</style>
